import { useTranslation } from 'react-i18next';
import { Helmet } from 'react-helmet-async';
import { motion } from 'framer-motion';
import { useState } from 'react';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { toast } from 'sonner';
import { useContact } from '@/hooks/useContact';
import { ContactFormData } from '@/lib/api/contact';
import { useSEOConfig, generateHreflangTags, generateStructuredData } from '@/lib/seo';

export default function AboutContact() {
  const { t } = useTranslation();
  const { isSubmitting, submitForm, validateForm } = useContact();
  const seoConfig = useSEOConfig({
    title: `${t('header.contact')} - 豆豆Pay`,
    description: t('seo.pages.aboutContact.description')
  });
  const hreflangTags = generateHreflangTags('/about/contact');
  const structuredData = generateStructuredData(seoConfig, 'website');

  const [formData, setFormData] = useState<ContactFormData>({
    name: '',
    email: '',
    company: '',
    subject: '',
    message: ''
  });

  const [errors, setErrors] = useState<Partial<Record<keyof ContactFormData, string>>>({});
  const [touched, setTouched] = useState<Partial<Record<keyof ContactFormData, boolean>>>({});

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));

    // 清除错误
    if (errors[name as keyof ContactFormData]) {
      setErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  // 处理输入失焦
  const handleBlur = (field: keyof ContactFormData) => {
    setTouched(prev => ({
      ...prev,
      [field]: true
    }));

    // 实时验证
    const validation = validateForm(formData);
    if (validation.errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: validation.errors[field]
      }));
    }
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 标记所有字段为已触碰
    const allTouched = Object.keys(formData).reduce((acc, key) => {
      acc[key as keyof ContactFormData] = true;
      return acc;
    }, {} as typeof touched);
    setTouched(allTouched);

    // 验证表单
    const validation = validateForm(formData);
    if (!validation.isValid) {
      setErrors(validation.errors);
      toast.error(t('aboutPages.contact.formValidationError'));
      return;
    }

    // 提交表单 - 调用真实的API
    const success = await submitForm(formData);
    if (success) {
      // 重置表单
      setFormData({
        name: '',
        email: '',
        company: '',
        subject: '',
        message: ''
      });
      setErrors({});
      setTouched({});
    }
  };
  
  // 联系信息数据
  const contactInfo = [
    {
      title: t('aboutPages.contact.headquartersAddress'),
      content: t('aboutPages.contact.fullAddress'),
      icon: "fa-map-marker-alt"
    },
    {
      title: t('aboutPages.contact.phone'),
      content: "+090-9833-9211",
      icon: "fa-phone"
    },
    {
      title: t('aboutPages.contact.email'),
      content: "dodo@mamepay.com",
      icon: "fa-envelope"
    },
    {
      title: t('aboutPages.contact.businessHours'),
      content: t('aboutPages.contact.businessHoursDetail'),
      icon: "fa-clock"
    }
  ];
  
  return (
    <div className="min-h-screen flex flex-col bg-white">
      <Helmet>
        {/* Basic Meta Tags */}
        <title>{seoConfig.title}</title>
        <meta name="description" content={seoConfig.description} />
        <meta name="keywords" content={seoConfig.keywords} />

        {/* Canonical URL */}
        <link rel="canonical" href={seoConfig.url} />

        {/* Open Graph / Facebook */}
        <meta property="og:title" content={seoConfig.title} />
        <meta property="og:description" content={seoConfig.description} />
        <meta property="og:image" content={seoConfig.image} />
        <meta property="og:url" content={seoConfig.url} />
        <meta property="og:locale" content={seoConfig.locale} />
        <meta property="og:site_name" content={seoConfig.siteName} />

        {/* Twitter */}
        <meta name="twitter:title" content={seoConfig.title} />
        <meta name="twitter:description" content={seoConfig.description} />
        <meta name="twitter:image" content={seoConfig.image} />

        {/* Hreflang tags for multilingual SEO */}
        {hreflangTags.map((tag, index) => (
          <link key={index} rel={tag.rel} hrefLang={tag.hreflang} href={tag.href} />
        ))}

        {/* Structured Data */}
        <script type="application/ld+json">
          {JSON.stringify(structuredData)}
        </script>
      </Helmet>
      
      <Header />
      
      <main className="flex-grow">
        {/* 页面标题区域 */}
        <section className="py-16 md:py-24 bg-gradient-to-r from-green-50 to-teal-50">
          <div className="container mx-auto px-4">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8 }}
              className="max-w-3xl mx-auto text-center"
            >
              <h1 className="text-3xl md:text-5xl font-bold text-gray-900 mb-6">
                {t('header.contact')}
              </h1>
              <div className="w-20 h-1 bg-green-500 mx-auto mb-8 rounded-full"></div>
              <p className="text-lg md:text-xl text-gray-700 leading-relaxed">{t('aboutPages.contact.welcome')}</p> 
            </motion.div>
          </div>
        </section>
        
        {/* 联系信息和表单 */}
        <section className="py-20 bg-white">
          <div className="container mx-auto px-4">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-16">
              {/* 联系信息 */}
              <motion.div
                initial={{ opacity: 0, x: -30 }}
                whileInView={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8 }}
                viewport={{ once: true }}
              >
                <h2 className="text-2xl md:text-3xl font-bold text-gray-900 mb-6">{t('aboutPages.contact.contactMethods')}</h2>
                <div className="w-16 h-1 bg-green-500 mb-8 rounded-full"></div>
                
                <div className="space-y-8">
                  {contactInfo.map((info, index) => (
                    <div key={index} className="flex items-start">
                      <div className="text-green-600 mr-4 mt-1">
                        <i className={`fa-solid ${info.icon} text-xl`}></i>
                      </div>
                      <div>
                        <h3 className="font-bold text-gray-900 mb-1">{info.title}</h3>
                        <p className="text-gray-700">{info.content}</p>
                      </div>
                    </div>
                  ))}
                </div>
                
                {/* 地图 */}
                <div className="mt-12 rounded-xl overflow-hidden shadow-lg h-80 bg-gray-200 relative">
                  <img 
                    src="https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=tokyo%20city%20map%2C%20roppongi%20district%2C%20office%20location&sign=268f827defe43f330a4e448b1961e2b3" 
                    alt={t('aboutPages.contact.companyLocationMapAlt')} 
                    className="w-full h-full object-cover"
                  />
                  <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
                    <div className="text-white text-center p-6">
                      <h3 className="text-xl font-bold mb-2">{t('aboutPages.contact.tokyoHeadquarters')}</h3>
                      <p className="mb-4">{t('aboutPages.contact.clickMap')}</p>
                      <button className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md transition-colors">
                        {t('aboutPages.contact.viewMap')}
                      </button>
                    </div>
                  </div>
                </div>
                
                {/* 社交媒体 */}
                <div className="mt-12">
                  <h3 className="font-bold text-gray-900 mb-4">{t('aboutPages.contact.followUs')}</h3>
                  <div className="flex space-x-4">
                    <a href="#" className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center text-gray-700 hover:bg-green-100 hover:text-green-600 transition-colors">
                      <i className="fa-brands fa-twitter"></i>
                    </a>
                    <a href="#" className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center text-gray-700 hover:bg-green-100 hover:text-green-600 transition-colors">
                      <i className="fa-brands fa-linkedin"></i>
                    </a>
                    <a href="#" className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center text-gray-700 hover:bg-green-100 hover:text-green-600 transition-colors">
                      <i className="fa-brands fa-facebook"></i>
                    </a>
                    <a href="#" className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center text-gray-700 hover:bg-green-100 hover:text-green-600 transition-colors">
                      <i className="fa-brands fa-instagram"></i>
                    </a>
                  </div>
                </div>
              </motion.div>
              
              {/* 联系表单 */}
              <motion.div
                initial={{ opacity: 0, x: 30 }} 
                whileInView={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8, delay: 0.3 }}
                viewport={{ once: true }}
              >
                <h2 className="text-2xl md:text-3xl font-bold text-gray-900 mb-6">{t('aboutPages.contact.sendMessage')}</h2>
                <div className="w-16 h-1 bg-green-500 mb-8 rounded-full"></div>
                
                <form onSubmit={handleSubmit} className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('aboutPages.contact.name')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        id="name"
                        name="name"
                        value={formData.name}
                        onChange={handleInputChange}
                        onBlur={() => handleBlur('name')}
                        disabled={isSubmitting}
                        className={`w-full px-4 py-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 ${
                          errors.name && touched.name ? 'border-red-500' : 'border-gray-300'
                        }`}
                        placeholder={t('aboutPages.contact.name')}
                      />
                      {errors.name && touched.name && (
                        <p className="mt-1 text-sm text-red-600">{t(`aboutPages.contact.${errors.name}`)}</p>
                      )}
                    </div>
                    <div>
                      <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('aboutPages.contact.email')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="email"
                        id="email"
                        name="email"
                        value={formData.email}
                        onChange={handleInputChange}
                        onBlur={() => handleBlur('email')}
                        disabled={isSubmitting}
                        className={`w-full px-4 py-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 ${
                          errors.email && touched.email ? 'border-red-500' : 'border-gray-300'
                        }`}
                        placeholder={t('aboutPages.contact.email')}
                      />
                      {errors.email && touched.email && (
                        <p className="mt-1 text-sm text-red-600">{t(`aboutPages.contact.${errors.email}`)}</p>
                      )}
                    </div>
                  </div>

                  <div>
                    <label htmlFor="company" className="block text-sm font-medium text-gray-700 mb-1">
                      {t('aboutPages.contact.companyName')}
                    </label>
                    <input
                      type="text"
                      id="company"
                      name="company"
                      value={formData.company}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                      className="w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                      placeholder={t('aboutPages.contact.companyName')}
                    />
                  </div>

                  <div>
                    <label htmlFor="subject" className="block text-sm font-medium text-gray-700 mb-1">
                      {t('aboutPages.contact.subject')} <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="subject"
                      name="subject"
                      value={formData.subject}
                      onChange={handleInputChange}
                      onBlur={() => handleBlur('subject')}
                      disabled={isSubmitting}
                      className={`w-full px-4 py-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 ${
                        errors.subject && touched.subject ? 'border-red-500' : 'border-gray-300'
                      }`}
                      placeholder={t('aboutPages.contact.subject')}
                    />
                    {errors.subject && touched.subject && (
                      <p className="mt-1 text-sm text-red-600">{t(`aboutPages.contact.${errors.subject}`)}</p>
                    )}
                  </div>

                  <div>
                    <label htmlFor="message" className="block text-sm font-medium text-gray-700 mb-1">
                      {t('aboutPages.contact.message')} <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id="message"
                      name="message"
                      rows={5}
                      value={formData.message}
                      onChange={handleInputChange}
                      onBlur={() => handleBlur('message')}
                      disabled={isSubmitting}
                      className={`w-full px-4 py-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 ${
                        errors.message && touched.message ? 'border-red-500' : 'border-gray-300'
                      }`}
                      placeholder={t('aboutPages.contact.message')}
                    />
                    {errors.message && touched.message && (
                      <p className="mt-1 text-sm text-red-600">{t(`aboutPages.contact.${errors.message}`)}</p>
                    )}
                    <p className="mt-1 text-sm text-gray-500">
                      {formData.message.length}/1000 {t('aboutPages.contact.characters')}
                    </p>
                  </div>

                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className={`w-full px-6 py-3 text-white font-medium rounded-md transition-colors shadow-md hover:shadow-lg flex items-center justify-center ${
                      isSubmitting
                        ? 'bg-gray-400 cursor-not-allowed'
                        : 'bg-green-600 hover:bg-green-700'
                    }`}
                  >
                    {isSubmitting ? (
                      <>
                        <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                        {t('aboutPages.contact.sending')}
                      </>
                    ) : (
                      <>
                        <i className="fa-solid fa-paper-plane mr-2"></i>
                        {t('aboutPages.contact.sendMessageBtn')}
                      </>
                    )}
                  </button>
                </form>
              </motion.div>
            </div>
          </div>
        </section>
      </main>
      
      <Footer />
    </div>
  );
}
